昨晚在電腦前莫名其妙被周公抓走,還好趕在灰姑娘的午夜 12 點前魂魄歸來、踩線發文,看來這幾天的文都在敘述概念(Git / HTML)……實在太催眠了。
為防又不小心被周公抓去太久而在昏迷中斷賽(為什麼不提早發!!),決定不照目錄寫作了(真是個任性的傢伙R)!
接下來直接來寫實用的範例吧!畢竟已經寫到快第 10 篇,還沒寫幾行 code ,甘那母湯~
元素置中是調控 CSS 時必然會遇到的問題,也是 Junior 前端工程師面試的熱門考題。
這篇列出常見的置中方式,設定題目條件:
<div class="container">
  <div class="box">
  </div>
</div>
.container{
    display: flex;
    justify-content: center; 
    align-items: center; 
}
justify-content:center  主軸對齊方式:居中align-items:center   次軸對齊方式:居中.container{
    display: flex;
    
    .box{
        margin: auto;
    }
}
margin: auto:將剩餘空間自動分配display 設為  grid / inline-flex / inline-grid 定義完整空間。.container{
    position: relative; 
    
    .box{
        position: absolute; 
        top: 0;             
        bottom: 0;           
        left: 0;        
        right: 0;
        margin: auto;      
    }
}
position: absolute 指定 top / right / bottom / left 時是以「第一個有定位的父層容器」為位移基準。position 為 relative / absolute / fixed
relative,因為 relative 在未指定 top / right / bottom / left 時不會有任何改變。top / right / bottom / left 指定為 0 時,會自動計算為可運用的空間。margin: auto:將剩餘空間做自動分配.container{
    position: relative;
    
    .box{
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
    }
}
position: absolute 依據其「有定位的父層」做位移。top: 50%、left: 50% 進行向下、左位移 50%:transform: translate(-50%,-50%) 才可真正置中。.container{
    
    .box{
        position: relative;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%)
    }
}
position: relative 指定 top / right / bottom / left 時為原本位置做偏移。.container{
    text-align: center;
    font-size: 0;
    
    &:after{
        content: '';
        height: 100%;
        vertical-align: middle;
        display: inline-block;
        width: 0px;
    }
    
    .box{
        display: inline-block;
        vertical-align: middle;
        
    }
}
個人 Blog: https://eudora.cc/
Google 查詢語法又導向你的文章了XD
真的是太感謝你了))受我一拜
p.s 寫法2 少了一個冒號喔
也是給自己的筆記整理~有幫助到你的話就太好了^^
已修正~謝嚕!